// pages/template/orderList.js
const app = getApp()
import Api from '../../utils/api';
import util from '../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    timer:null,
    userIdentityStatus: 0 , //0 只有代理商， 1商户
    orderStatusText: ['未付款', '待处理', '配送中', '已完成'],
    orderStatusArr: ['UNPAY', 'WAITSEND', 'SENDED','WAITCOMMENT'],
    orderStatusIndex: 1,
    deliveryTypeText: ['壹配送到家', '物流配送', '到店自提','到店消费'],
    deliveryTypeArr: ['YPS', 'POST', 'ZT','CONSUME'],
    deliveryTypeIndex: 0,
    shopId: "", //商户id
    orderId: '', //订单编号
    showOrder: true, //展示订单管理列表
    showOrderDetail: false, //订单详情页
    goodsInfo: '', //订单详情信息
    goodsList:[], //
    page:1 ,
    size: 10,
    userIdentity: "", //用户身份 merchant agent
    newGoodsList: [], //导入列表数据
    seedIndex: 0, //代发货列表索引
    seedStatus: false, //代发货状态

    //导入相关信息
    itemSizeOptionsText: ["小件(30x30x30cm)", "中件(50x50x30cm)", "大件(1x1x0.5m)", "小型货运(1x1.5x1.5m)", "中型货运(2x1.5x1.5m)"],//物品尺寸
    itemSizeOptionsIndex: 0,
    itemSizeOptions: ["SMALL", "MIDDLE", "BIG", "VERY_BIG", "HUGE"],
    itemTypeOptions: ["食品", "饮料", "鲜花", "蛋糕", "水果", "生鲜", "文件", "证件", "数码", "衣服", "建材", "其他"],//物品类型
    itemTypeOptionsIndex: 0,
    itemVehicleOptionsText: ['机动三轮车', '面包车', '小货车', '中型货车'],//交通工具
    itemVehicleOptionsIndex: 0,
    itemVehicleOptions: ['MOBILE_TRICYCLE', 'VAN', 'TRUCK','MIDDLE_TRUCK'],
    starter: {}, //发件人
    importOrderList: [], //导入订单数组
    importOrderPrice: 0, //总价格
    importPriceAdditional:  0, //加价的价格
    bigCustomer: '', //大商户id 
    countBtn: true, //计算价格解锁
    yksBaseUrl: 'https://yikesong.cc:8080',
    orderUserShow: true, //
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;
    //console.log(options.shopId)
    //options.shopId = "1146268760156540928";
    if (options.shopId != undefined){ //商户、店铺
      _this.setData({
        shopId: options.shopId,
        userIdentity: "merchant"
      })
      let tokenObject = wx.getStorageSync('tokenObject');
      if (tokenObject.access_tokenUser.roles.indexOf("agent") != -1){
        _this.setData({
          userIdentityStatus: 1,
        })
      }
      _this.queryMerchant() //查询商户订单列表 merchant
      _this.merchantId();
    }else{  //拼团、代理商
      console.log(1111)
      _this.setData({
        userIdentity: "agent"
      })
      _this.agentId();
      _this.queryAgent();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    if (_this.data.seedStatus){
      let arr = _this.data.goodsList;
      arr.splice(seedIndex,1);
      _this.setData({
        seedStatus: false,
        goodsList: arr,
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //console.log("上拉刷新")
    // let _this = this;
    // _this.setData({
    //   page: 1,
    //   goodsList: [],
    // })
    // wx.showLoading({
    //   title: '刷新中',
    // })
    // _this.queryMerchant(function () {
    //   setTimeout(function () {
    //     wx.hideLoading()
    //   }, 2000)
    // });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //console.log("下拉加载")
    let _this = this;
    if (_this.data.page < _this.data.totalPages) {
      _this.setData({
        page: _this.data.page + 1,
      })
      wx.showLoading({
        title: '加载中',
      })
      if (_this.data.userIdentity = "merchant"){
        _this.queryMerchant(function () {
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
        });
      }else{
        _this.queryAgent(function () {
          setTimeout(function () {
            wx.hideLoading()
          }, 2000)
        });
      }
      
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    app.globalData.otherPageHideFlag = true;
  },
  //查询商户订单列表 merchant
  queryMerchant(callback){
    let _this = this;
    let data = {
      shopId: _this.data.shopId,
      orderId: _this.data.orderId,
      deliveryType: _this.data.deliveryTypeArr[_this.data.deliveryTypeIndex],
      sort: "desc",
      orderStatus: _this.data.orderStatusArr[_this.data.orderStatusIndex],
    }
    Api.queryMerchant(data, _this.data.page, _this.data.size).then( res => {
      console.log("商户",res)
      let list = res.data.data.dataList;
      list.forEach(function(item,index,arr){
        item.checked = false;
        item.order.orderTime = util.formatTime(new Date(item.order.orderTime))

      })
      _this.setData({
        goodsList: _this.data.goodsList.concat(list),
        totalPages: res.data.data.totalPages
      });
      //console.log(_this.data.goodsList);
      (callback && (typeof callback) === "function") && callback();
    })
  },

 //查询代理商订单接口 agent
  queryAgent(callback) {
    let _this = this;
    let data = {
      orderId: _this.data.orderId,
      deliveryType: _this.data.deliveryTypeArr[_this.data.deliveryTypeIndex],
      sort: "desc",
      orderStatus: _this.data.orderStatusArr[_this.data.orderStatusIndex],
    }
    //console.log("查询代理商订单接口",data)
    Api.queryAgent(data, _this.data.page, _this.data.size).then(res => {
      console.log("查询代理商订单接口",res)
      let list = res.data.data.dataList;
      list.forEach(function (item, index, arr) {
        item.checked = false;
        item.order.orderTime = util.formatTime(new Date(item.order.orderTime))

      })
      _this.setData({
        goodsList: _this.data.goodsList.concat(list),
        totalPages: res.data.data.totalPages
      });
      //console.log(_this.data.goodsList);
      (callback && (typeof callback) === "function") && callback();
    })
  },

  //切换tab
  tabClick(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    _this.setData({
      orderStatusIndex: index,
      goodsList: [],
      page: 1,
      orderId: '',
    })
    wx.showLoading({
      title: '加载中',
    })
    if (_this.data.userIdentity == "merchant"){
      _this.queryMerchant(function () {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      });
    }else{
      _this.queryAgent(function () {
        setTimeout(function () {
          wx.hideLoading()
        }, 2000)
      });
    }
    
  },
  //配送类型切换
  bindPickerChange(e){
    console.log(e)
    let _this = this;
    _this.setData({
      deliveryTypeIndex: e.detail.value,
      goodsList: [],
      page: 1
    });
    wx.showLoading({
      title: '加载中',
    })
    console.log(_this.data.deliveryTypeArr[_this.data.deliveryTypeIndex])
    _this.queryMerchant(function () {
      setTimeout(function () {
        wx.hideLoading()
      }, 2000)
    });
  },

  //待处理勾选中
  checkboxChange(e){
    console.log(e)
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.goodsList;
    arr[index].checked = !arr[index].checked;
    _this.setData({
      goodsList: arr
    })
    console.log(_this.data.goodsList)
  },

  //展示订单信息
  showOrderClick(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    _this.setData({
      goodsInfo: _this.data.goodsList[index],
      showOrderDetail: true,
    })
    console.log(_this.data.goodsInfo)
  },
  //收起订单信息
  hideOrderClick(){
    let _this = this;
    _this.setData({
      showOrderDetail: false,
    })
  },

  //待发货
  seedGoodsClick(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    //console.log(_this.data.goodsList[index]);
    _this.setData({
      seedIndex: index,
    })
    wx.navigateTo({
      url: `/pages/template/queryLogistics?orderId=${_this.data.goodsList[index].order.id}`,
    })
  },

  //查询订单编号
  orderId(e){
    console.log(e)
    let _this = this;
    _this.setData({
      orderId: e.detail.value
    })
  },

  //检索
  seachOrder(){
    let _this = this;
    console.log(_this.data.orderId)
    _this.setData({
      goodsList: [],
      page: 1,
    })
    if (_this.data.userIdentity == "merchant"){
      wx.showLoading({
        title: '加载中',
      });
      _this.queryMerchant(function () {
        setTimeout(function () {
          wx.hideLoading();
        }, 2000);
      });
    }
  },

  //扫码核销
  writeOff(){
    let _this  = this;
    wx.scanCode({
      //onlyFromCamera: true,
      success(res) {
        console.log(res)
        Api.scannerOrder(res.result).then( res => {
          //console.log(res.data)
          wx.showLoading({
            title: '加载中',
          })
          _this.queryMerchant(function () {
            setTimeout(function () {
              wx.hideLoading()
            }, 1000)
          });
        })
      }
    })
  },


  //红包核销
  writeOffRed() {
    let _this = this;
    wx.scanCode({
      //onlyFromCamera: true,
      success(res) {
        Api.scannerRedPage(_this.data.shopId, res.result).then(res => {
          console.log(res)
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        })
      }
    })
  },

  //批量导入
  batchClick(){
    let _this = this;
    let arr = _this.data.goodsList;
    let newArr = []; //newGoodsList
    arr.forEach(function(item,index,arr){
      if (item.checked){
        newArr.push(item);
      }
    });
    console.log(newArr)
    if (newArr.length <= 0){
      return;
    }
    let currentShop = wx.getStorageSync("shopInfo");
    let starter = {
      name: currentShop.shopName,
      phonenumber: currentShop.contact,
      longitude: currentShop.longitude,
      latitude: currentShop.latitude,
      addressName: `${currentShop.province}${currentShop.city}${currentShop.town}`,
      addressDetail: currentShop.addressDetail,
      poiName: currentShop.addressDetail
    };
    let importOrderList = [];
    newArr.forEach(function(item,index,arr){
      //组装收件人
      let receiveAddress = item.receiveAddress;
      let receiver = {
        name: receiveAddress.name,
        phonenumber: receiveAddress.telephone,
        longitude: receiveAddress.longitude,
        latitude: receiveAddress.latitude,
        addressName: `${receiveAddress.province}${receiveAddress.city}${receiveAddress.town}`,
        addressDetail: receiveAddress.detailAddress,
        poiName: receiveAddress.detailAddress
      };
      //组装订单信息
      let orderItemList = item.orderItems;
      let order = item.order;
      let importOrder = {
        starter: starter,
        receiver: receiver,
        item: {
          name:
            !orderItemList || orderItemList.length < 0
              ? "惠生活商品"
              : `${orderItemList[0].title}${
              orderItemList.length > 1 ? "等..." : ""
              }`,
          type: "食品",
          size: "SMALL",
          weight: 5,
          remark: order ? order.remarks : ""
        },
        vehicle: null,  //交通工具 默认为null
        orderType: "MergeOrder", //
        payType: "BIG_CUSTOMER_RECHARGE",
        payMode: "ImmediatePay",
        linkOrderId: item.order.id, //当前订单id
        linkUrl: `http://peter.xiaomiqiu.com/api/common/pay/order/handler/notify/`,
      };
     importOrderList.push(importOrder);

    });
    //console.log(importOrderList)
    _this.setData({
      newGoodsList: newArr,
      showOrder: false,
      importOrderList: importOrderList,
      starter: starter
    })
  },

  //关闭导入页面
  colseOrderClick(){
    let _this  = this;
    _this.setData({
      showOrder: true,
      importOrderPrice: 0,
      importPriceAdditional: 0,
    })
  },

  //物品尺寸
  itemSizeOptionsClick(e){
    //console.log(e)
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.importOrderList;
   // itemVehicleOptionsText: ['机动三轮车', '面包车', '小货车', '中型货车'],//交通工具
     // itemVehicleOptionsIndex: 0,
    //    itemVehicleOptions: ['MOBILE_TRICYCLE', 'VAN', 'TRUCK', 'MIDDLE_TRUCK']
    //itemSizeOptions: ["SMALL", "MIDDLE", "BIG", "VERY_BIG", "HUGE"],
    //console.log(e.detail.value)
    if (e.detail.value <= 1){
      arr[index].vehicle = null;
    }else if (e.detail.value == 2){
      _this.setData({
        itemVehicleOptionsText: ['机动三轮车', '面包车', '小货车'],
        itemVehicleOptionsIndex: 0,
        itemVehicleOptions: ['MOBILE_TRICYCLE', 'VAN', 'TRUCK']
      })
      arr[index].vehicle = _this.data.itemVehicleOptions[_this.data.itemVehicleOptionsIndex];
    } else if (e.detail.value == 3){
      _this.setData({
        itemVehicleOptionsText: ['小货车', '中型货车'],
        itemVehicleOptionsIndex: 0,
        itemVehicleOptions: ['TRUCK', 'MIDDLE_TRUCK']
      })
      arr[index].vehicle = _this.data.itemVehicleOptions[_this.data.itemVehicleOptionsIndex];
    } else if (e.detail.value == 4) {
      _this.setData({
        itemVehicleOptionsText: [ '中型货车'],
        itemVehicleOptionsIndex: 0,
        itemVehicleOptions: ['MIDDLE_TRUCK']
      })
      arr[index].vehicle = _this.data.itemVehicleOptions[_this.data.itemVehicleOptionsIndex];
    }
    
    //console.log(arr[index])
    arr[index].item.size = _this.data.itemSizeOptions[e.detail.value];
    _this.setData({
      itemSizeOptionsIndex: e.detail.value,
      importOrderList: arr

    })
    console.log(_this.data.importOrderList)
  },
  //物品类型
  itemTypeOptionsClick(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.importOrderList;
    arr[index].item.type = _this.data.itemTypeOptions[e.detail.value]
    _this.setData({
      itemTypeOptionsIndex: e.detail.value,
      importOrderList: arr
    })
    //console.log(_this.data.importOrderList)
  },

  //交通工具
  itemVehicleOptionsClick(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.importOrderList;
    arr[index].vehicle = _this.data.itemVehicleOptions[e.detail.value]
    _this.setData({
      itemVehicleOptionsIndex: e.detail.value,
      importOrderList: arr
    })
    //console.log(_this.data.importOrderList)
  },


  //获取重量
  getweight(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.importOrderList;
    arr[index].item.weight = e.detail.value
    _this.setData({
      importOrderList: arr
    })
    //console.log(_this.data.importOrderList);
  },

  //备注信息
  getremark(e){
    let _this = this;
    let index = e.currentTarget.dataset.index;
    let arr = _this.data.importOrderList;
    arr[index].item.remark = e.detail.value
    _this.setData({
      importOrderList: arr
    })
    //console.log(_this.data.importOrderList);
  },
  //导入订单价格预览
  importOrderPrePrice() {
    var _this = this;
    if (!_this.data.countBtn){
      return;
    }
    _this.setData({
      importOrderPrice: 0,
      importPriceAdditional: 0,
      countBtn: false,
    })
    // let timer = null;
    let taskStatus = true; //任务总状态
    let successCount = 0; //导入成功的订单个数
    let arr = _this.data.importOrderList; 
    let importLength = _this.data.importOrderList.length; //需要导入订单的长度
    let currentIndex = 0;
    let headers = {
      Accept: 'application/json',
      Authorization: 'Bearer ' + wx.getStorageSync("bigCustomerToken").access_token,
      RefreAuthorization: wx.getStorageSync("bigCustomerToken").refresh_token,
    };
   var timer = setInterval(function () {
      if (currentIndex < importLength) {
        //正在导入
        orderPriceModelPre(currentIndex++);
      } else {
        //预览结束
        setTimeout(function(){
          _this.setData({
            countBtn: true
          })
        },1000)
        if (taskStatus) {
          //全部预览成功
        } else {
          //有一个或多个订单预览异常
          if (successCount <= 0) {
            _this.$message.error("预览订单失败");
          } else {
            wx.showModal({
              title: '订单预览',
              content: `订单预览异常,成功预览${successCount}个,预览失败订单${importLength - successCount}个!`,
              success(res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            });
          }
        }
        clearInterval(_this.data.timer);
      }
    }, 100);
    _this.setData({
      timer: timer
    })

    function orderPriceModelPre(i) {
      wx.request({
        url: `${_this.data.yksBaseUrl}/api/bigcustomer/${_this.data.bigCustomer.id}/importedOrders/pricePreview`,
        data: JSON.stringify(arr[i]),
        header: headers,
        method: "POST",
        success: function (res) {
          console.log(res)
          if (res.data.status === 1) {
            console.log("响应成功", res.data.status);
            arr[i].price = res.data.data.price.toFixed(2);
            arr[i].distancePreview = res.data.data.distance;
            arr[i].priceOrigin = res.data.data.priceOrigin;
            arr[i].responsePrice = true;
            _this.setData({
              importOrderPrice: _this.data.importOrderPrice + res.data.data.price,
              priceAdditional: _this.data.priceAdditional + res.data.data.priceAdditional,
            })
          } else {
            arr[i].responsePrice = false;
          }
          _this.setData({
            importOrderList: arr
          })
          console.log(_this.data.importOrderList)
          successCount++;
        },
        fail: function (res) {
          taskStatus = false;
        },
        complete: function (res) { },
      })
    }

  },

  //获取商户id
  merchantId(){
    let _this  = this;
    Api.merchantId().then( res => {
      console.log("获取商户id",res)
      wx.setStorageSync("bigCustomerToken", res.data.data.generalIdTokenDto.tokenObject)
      _this.setData({
        bigCustomer: res.data.data.generalIdTokenDto
      })
    });
  },

   //获取代理商id
  agentId(){
    let _this = this;
    Api.agentId().then(res => {
      console.log("获取代理商id",res);

    });
  },

  //导入按钮
  importClick(){
    let _this = this;
    let headers = {
      Accept: 'application/json',
      Authorization: 'Bearer ' + wx.getStorageSync("bigCustomerToken").access_token,
      RefreAuthorization: wx.getStorageSync("bigCustomerToken").refresh_token,
    };
    wx.request({
      url: `${_this.data.yksBaseUrl}/api/bigcustomer/${_this.data.bigCustomer.id}/importedOrders/canImportOrder`,
      data: JSON.stringify(_this.data.importOrderList),
      header: headers,
      method: "POST",
      success: function (res) {
        console.log("查看是否能导入", res);
        if (res.data.data){
          let text = ''
          if (_this.data.priceAdditional){
            text = `因恶劣天气、高峰期、夜间等原因每单已额外加价${_this.data.priceAdditional}元\r\n`
          }
          wx.showModal({
            title: '温馨提示',
            content: `${text}当前导入订单量：${_this.data.importOrderList.length}个,\r\n已选择导入方式：导入拼单,\r\n合计总配送费：${_this.data.importOrderPrice}元`,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                //执行导入方法
                _this.importOrder();
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          });
        }else{
          wx.showToast({
            title: '余额不足',
            icon: 'none',
            duration: 2000
          })
        }

      },
      fail: function (res) {
        wx.showToast({
          title: '服务器繁忙',
          icon: 'none',
          duration: 2000
        })
      },
      complete: function (res) { },
    });

    

  },

  //导入壹配送订单
  importOrder() {
    var _this = this;
    // var timer = null; //定时器
    var taskStatus = true; //任务总状态
    var successCount = 0; //导入成功的订单个数
    let arr = _this.data.importOrderList;
    var importLength = _this.data.importOrderList.length; //需要导入订单的长度
    var currentIndex = 0; //当前索引
    let headers = {
      Accept: 'application/json',
      Authorization: 'Bearer ' + wx.getStorageSync("bigCustomerToken").access_token,
      RefreAuthorization: wx.getStorageSync("bigCustomerToken").refresh_token,
    };
   var timer = setInterval(function () {
      if (currentIndex < importLength) {
        //正在导入
        importOrder(currentIndex++);
      } else {
        //导入结束
        if (taskStatus) {
          //全部导入成功
          wx.showToast({
            title: '导入订单成功',
            icon: 'success',
            duration: 2000
          })
        } else {
          //有一个或多个订单导入异常
          if (successCount <= 0) {
            
          } else {
           
          }
        }
        //清除定时器
        clearInterval(_this.data.timer); //清楚定时器
        //刷新列表
        _this.queryMerchant(); //重新加载数据
        //清除遗留数据
        _this.setData({
          importOrderList: [],
          showOrder: true,
          importOrderPrice: 0,
          importPriceAdditional: 0,
        })
      }
    }, 800);
    _this.setData({
      timer:timer,
    })
    //导入订单
    function importOrder(i) {
      wx.request({
        url: `${_this.data.yksBaseUrl}/api/bigcustomer/${_this.data.bigCustomer.id}/importedOrders/orders`,
        data: JSON.stringify(arr[i]),
        header: headers,
        method: "POST",
        success: function (res) {
          console.log(res)
          if (res.data.status === 1) {
            let requestData = {
              orderId: _this.data.importOrderList[i].linkOrderId,
              sendOrderId: res.data.data.id,
              postPrice: 0
            };
            Api.linkOrder(requestData).then( res => {
              console.log("导入相关联", res)
              successCount++;
              _this.setData({
                page: 1,
                goodsList: [],
              })
              _this.queryMerchant();
            });
          } else {
            //下单失败
            taskStatus = false;
          }
          _this.setData({
            importOrderList: arr
          })
          console.log(_this.data.importOrderList)
          //successCount++;
        },
        fail: function (res) {
          taskStatus = false;
        },
        complete: function (res) { },
      })
    }
  },

  //
  orderUserHide(){
    let _this = this;
    _this.setData({
      orderUserShow: false,
    })
  },

  //
  orderUserShow(){
    let _this = this;
    _this.setData({
      orderUserShow: true,
    })
  },

  agentClick(){ //商户订单数据
    let _this = this;
    _this.setData({
      userIdentity: "merchant",
      page: 1,
      goodsList: [],
    });
    _this.queryMerchant() //查询商户订单列表 merchant
    _this.merchantId();
  },

  merchantClick(){ //代理订单数据
    let _this = this;
    _this.setData({
      userIdentity: "agent",
      page: 1,
      goodsList: [],
    });
    _this.agentId();
    _this.queryAgent();
  }

})